<template>
  <view class="index">
    <nut-sticky>
      <view>
        <view class="dpr-center-sb px-1 white-bg">
          <nut-searchbar
            v-model="query.keywords"
            style="width: 66%"
            disabled
            placeholder="搜索带货选品"
            input-background="#e9e9e9"
            @click="toSearch"
          >
            <template #leftin>
              <nut-icon color="#505050" size="14" name="search2"></nut-icon>
            </template>
          </nut-searchbar>
          <nut-button
            style="height: 32px; margin-right: 12px"
            plain
            type="primary"
            @click="Taro.navigateTo({ url: '/pages/business/index?c=inner' })"
            >我要合作</nut-button
          >
        </view>
      </view>
      <view class="dpc-center-center white-bg">
        <simple-tabs style="width: 90%" :items="categories" :value="query.category_id" @tab-change="handleTabClick" />
      </view>
    </nut-sticky>
    <view>
      <nut-swiper
        :init-page="0"
        :loop="true"
        auto-play="3000"
        height="150"
        :pagination-visible="true"
        style="height: 150px"
      >
        <nut-swiper-item>
          <image style="width: 100%" mode="aspectFill" src="https://doudaixuan.com/images/10.jpeg" />
        </nut-swiper-item>
        <nut-swiper-item>
          <image style="width: 100%" mode="aspectFill" src="https://doudaixuan.com/images/11.jpeg" />
        </nut-swiper-item>
        <nut-swiper-item>
          <image style="width: 100%" mode="aspectFill" src="https://doudaixuan.com/images/12.jpeg" />
        </nut-swiper-item>
      </nut-swiper>
      <proto-list :items="protoItems" @item-click="handleProtoClick" />
      <nut-empty v-if="!protoListLoading && !protoTotal" description="暂无商品" style="background-color: #fff" />
      <view class="ma-3">
        <load-more-bottom
          v-if="protoItems && protoItems.length >= query.limit"
          class="scroll-load-more"
          :loading="moreLoading"
          :no-more="noMore"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import './index.less';
import { getCurrentInstance, ref } from 'vue';
import Taro, {
  useLoad,
  usePullDownRefresh,
  useReachBottom,
  useShareAppMessage,
  useShareTimeline,
  useTitleClick,
} from '@tarojs/taro';
import { CategoryType, getCategoriesApi } from '@/api/categories';
import ProtoList from '@/components/proto-list/index.vue';
import LoadMoreBottom from '@/components/load-more-bottom/index.vue';
import { getProtoListApi, ProtoType } from '@/api/proto';
import SimpleTabs from '@/components/simple-tabs/index.vue';

const windowInfo = Taro.getWindowInfo();
const { proxy } = getCurrentInstance();
const query = ref({
  page: 1,
  limit: 6,
  category_id: '',
  sort_by: '',
  keywords: '',
});
const toSearch = () => {
  Taro.navigateTo({ url: '/pages/search/index' });
};
const scrollTop = ref(0);
const protoListLoading = ref(false);
const noMore = ref(true);
const categories = ref<CategoryType[]>([]);
const protoItems = ref<ProtoType[]>([]);
const protoTotal = ref<number>(0);
const sortType = ref([
  { text: '默认排序', value: '' },
  { text: '累计销量', value: 'sales' },
  { text: '佣金比例', value: 'commission_ratio' },
]);
const getCategories = () => {
  categories.value = [];
  categories.value.push({ id: '', name: '全部分类', icon: '' });
  getCategoriesApi({}).then((res) => {
    if (res.success) {
      categories.value = categories.value.concat(res.result);
    }
  });
};
const handleProtoClick = (proto: ProtoType) => {
  Taro.navigateTo({ url: `/pages/proto/detail/index?id=${proto.id}` });
};
const refreshLoading = ref(false);
const getProtoList = () => {
  if (protoListLoading.value === true) {
    return;
  }
  query.value.page = 1;
  protoListLoading.value = true;
  refreshLoading.value = true;
  getProtoListApi(query.value)
    .then((res) => {
      if (res.success) {
        protoItems.value = res.result.items;
        protoTotal.value = res.result.total;
        noMore.value = !res.result || !res.result.total || res.result.total < query.value.limit;
      }
    })
    .finally(() => {
      protoListLoading.value = false;
      refreshLoading.value = false;
    });
};
const moreLoading = ref(false);
const loadMore = () => {
  if (moreLoading.value || noMore.value) {
    return;
  }
  moreLoading.value = true;
  query.value.page += 1;
  setTimeout(() => {
    getProtoListApi(query.value)
      .then((res) => {
        if (res.success) {
          if (res.result.items && res.result.items.length) {
            protoItems.value = protoItems.value.concat(res.result.items);
            protoTotal.value = res.result.total;
            noMore.value = !res.result || !res.result.total || res.result.total < query.value.limit;
          } else {
            noMore.value = true;
          }
        }
      })
      .finally(() => {
        moreLoading.value = false;
      });
  }, 100);
};
useShareAppMessage((res) => {
  if (res.from === 'button') {
    // 来自页面内转发按钮
    console.log(res.target);
  }
  return {
    title: '抖带选 - 抖音达人带货选品快速变现平台',
  };
});

const handleTabClick = (tab) => {
  console.log(tab);
  if (!tab) {
    return;
  }
  query.value.category_id = tab.id;
  getProtoList();
};
useShareTimeline(() => {
  console.log('分享朋友圈');
  return {};
});

usePullDownRefresh(() => {
  console.log('下拉');
  setTimeout(() => {
    getCategories();
    getProtoList();
    Taro.stopPullDownRefresh();
  }, 300);
});
useTitleClick(() => {
  console.log('标题点击');
});
useReachBottom(() => {
  console.log('底部');
  loadMore();
});
useLoad(() => {
  getCategories();
  getProtoList();
});
</script>
